// 游戏状态管理 Store

import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { GameState, GameConfig, SaveSlot, GameEvent, Achievement } from '@/types'

export const useGameStore = defineStore('game', () => {
  // 状态
  const gameState = ref<GameState>({
    id: '',
    name: '',
    difficulty: 'normal',
    currentView: 'overview',
    gameTime: 0,
    realTime: 0,
    isPaused: false,
    speed: 1,
    version: '1.0.0',
    createdAt: Date.now(),
    lastSaved: Date.now(),
    achievements: [],
    statistics: {
      totalPlayTime: 0,
      resourcesGathered: {},
      buildingsBuilt: 0,
      technologiesResearched: 0,
      shipsBuilt: 0,
      battlesWon: 0,
      planetsColonized: 0
    }
  })

  const gameConfig = ref<GameConfig>({
    autoSave: true,
    autoSaveInterval: 300000, // 5分钟
    soundEnabled: true,
    musicEnabled: true,
    soundVolume: 0.8,
    musicVolume: 0.6,
    showTutorial: true,
    language: 'zh-CN',
    theme: 'dark',
    notifications: true,
    pauseOnFocusLoss: true
  })

  const saveSlots = ref<SaveSlot[]>([])
  const currentEvents = ref<GameEvent[]>([])
  const achievements = ref<Achievement[]>([])

  // 计算属性
  const isGameActive = computed(() => gameState.value.id !== '')
  const gameTimeFormatted = computed(() => {
    const hours = Math.floor(gameState.value.gameTime / 3600)
    const minutes = Math.floor((gameState.value.gameTime % 3600) / 60)
    return `${hours}h ${minutes}m`
  })

  const completedAchievements = computed(() => 
    achievements.value.filter(a => a.isUnlocked)
  )

  const achievementProgress = computed(() => {
    const total = achievements.value.length
    const completed = completedAchievements.value.length
    return total > 0 ? (completed / total) * 100 : 0
  })

  // 动作
  function createNewGame(name: string, difficulty: GameState['difficulty']) {
    gameState.value = {
      id: `game_${Date.now()}`,
      name,
      difficulty,
      currentView: 'overview',
      gameTime: 0,
      realTime: 0,
      isPaused: false,
      speed: 1,
      version: '1.0.0',
      createdAt: Date.now(),
      lastSaved: Date.now(),
      achievements: [],
      statistics: {
        totalPlayTime: 0,
        resourcesGathered: {},
        buildingsBuilt: 0,
        technologiesResearched: 0,
        shipsBuilt: 0,
        battlesWon: 0,
        planetsColonized: 0
      }
    }
  }

  function loadGame(saveSlot: SaveSlot) {
    if (saveSlot.gameState) {
      gameState.value = { ...saveSlot.gameState }
    }
  }

  function saveGame(): SaveSlot {
    const saveSlot: SaveSlot = {
      id: `save_${Date.now()}`,
      name: gameState.value.name,
      gameState: { ...gameState.value },
      timestamp: Date.now(),
      version: gameState.value.version,
      screenshot: '' // 可以添加截图功能
    }
    
    gameState.value.lastSaved = Date.now()
    
    // 添加到存档列表
    const existingIndex = saveSlots.value.findIndex(slot => slot.id === saveSlot.id)
    if (existingIndex >= 0) {
      saveSlots.value[existingIndex] = saveSlot
    } else {
      saveSlots.value.push(saveSlot)
    }
    
    return saveSlot
  }

  function pauseGame() {
    gameState.value.isPaused = true
  }

  function resumeGame() {
    gameState.value.isPaused = false
  }

  function setGameSpeed(speed: number) {
    gameState.value.speed = Math.max(0.1, Math.min(10, speed))
  }

  function changeView(view: GameState['currentView']) {
    gameState.value.currentView = view
  }

  function updateGameTime(deltaTime: number) {
    if (!gameState.value.isPaused) {
      gameState.value.gameTime += deltaTime * gameState.value.speed
      gameState.value.statistics.totalPlayTime += deltaTime
    }
    gameState.value.realTime += deltaTime
  }

  function addEvent(event: GameEvent) {
    currentEvents.value.push(event)
  }

  function removeEvent(eventId: string) {
    const index = currentEvents.value.findIndex(e => e.id === eventId)
    if (index >= 0) {
      currentEvents.value.splice(index, 1)
    }
  }

  function unlockAchievement(achievementId: string) {
    const achievement = achievements.value.find(a => a.id === achievementId)
    if (achievement && !achievement.isUnlocked) {
      achievement.isUnlocked = true
      achievement.unlockedAt = Date.now()
      
      // 添加到游戏状态的成就列表
      if (!gameState.value.achievements.includes(achievementId)) {
        gameState.value.achievements.push(achievementId)
      }
    }
  }

  function updateConfig(newConfig: Partial<GameConfig>) {
    gameConfig.value = { ...gameConfig.value, ...newConfig }
  }

  function updateStatistics(stats: Partial<GameState['statistics']>) {
    gameState.value.statistics = { ...gameState.value.statistics, ...stats }
  }

  // 初始化方法
  async function loadGameData() {
    try {
      console.log('正在加载游戏数据...')
      
      // 加载存档列表
      const savedGames = await loadSaveSlots()
      saveSlots.value = savedGames
      
      // 加载成就数据
      await loadAchievements()
      
      // 检查是否有自动保存
      const autoSave = saveSlots.value.find(slot => slot.id === 'autosave')
      if (autoSave) {
        console.log('发现自动保存，准备加载')
      }
      
      console.log('游戏数据加载完成')
    } catch (error) {
      console.error('加载游戏数据失败:', error)
      throw new Error('加载游戏数据失败')
    }
  }

  async function initializeStores() {
    try {
      console.log('正在初始化存储系统...')
      
      // 初始化各个子存储
      const { useResourcesStore } = await import('./resources')
      const resourcesStore = useResourcesStore()
      resourcesStore.initializeResources()
      
      console.log('存储系统初始化完成')
    } catch (error) {
      console.error('初始化存储系统失败:', error)
      throw new Error('初始化存储系统失败')
    }
  }

  async function loadUserSettings() {
    try {
      console.log('正在加载用户设置...')
      
      // 从本地存储或数据库加载用户设置
      const savedConfig = localStorage.getItem('star-conquest-config')
      if (savedConfig) {
        try {
          const config = JSON.parse(savedConfig)
          gameConfig.value = { ...gameConfig.value, ...config }
        } catch (parseError) {
          console.warn('解析用户设置失败，使用默认设置')
        }
      }
      
      console.log('用户设置加载完成')
    } catch (error) {
      console.error('加载用户设置失败:', error)
      throw new Error('加载用户设置失败')
    }
  }

  // 游戏控制方法
  function setCurrentView(view: GameState['currentView']) {
    gameState.value.currentView = view
  }

  function togglePause() {
    gameState.value.isPaused = !gameState.value.isPaused
  }

  function updatePlayTime(deltaTime: number) {
    gameState.value.statistics.totalPlayTime += deltaTime
  }

  // 事件管理方法
  function dismissCurrentEvent() {
    if (currentEvents.value.length > 0) {
      currentEvents.value.shift()
    }
  }

  function acknowledgeEvent(eventId: string) {
    removeEvent(eventId)
  }

  function makeEventChoice(eventId: string, choiceId: string) {
    const event = currentEvents.value.find(e => e.id === eventId)
    if (event) {
      console.log(`处理事件选择: ${eventId} -> ${choiceId}`)
      // 这里应该处理选择的效果
      removeEvent(eventId)
    }
  }

  function clearProcessedEvents() {
    currentEvents.value = currentEvents.value.filter(event => !event.processed)
  }

  function markEventAsProcessed(eventId: string) {
    const event = currentEvents.value.find(e => e.id === eventId)
    if (event) {
      event.processed = true
    }
  }

  function updateLastEventTime(gameTime: number) {
    // 更新最后事件时间
    gameState.value.lastEventTime = gameTime
  }

  function processEventChoice(eventId: string, choiceId: string) {
    makeEventChoice(eventId, choiceId)
  }

  // 成就系统方法
  function isAchievementUnlocked(achievementId: string): boolean {
    const achievement = achievements.value.find(a => a.id === achievementId)
    return achievement ? achievement.isUnlocked : false
  }

  function getEvent(eventId: string): GameEvent | undefined {
    return currentEvents.value.find(e => e.id === eventId)
  }

  // 辅助方法
  async function loadSaveSlots(): Promise<SaveSlot[]> {
    try {
      // 这里应该从数据库或本地存储加载存档
      const savedSlots = localStorage.getItem('star-conquest-saves')
      if (savedSlots) {
        return JSON.parse(savedSlots)
      }
      return []
    } catch (error) {
      console.error('加载存档列表失败:', error)
      return []
    }
  }

  async function loadAchievements() {
    try {
      // 初始化成就数据
      achievements.value = [
        {
          id: 'first_colony',
          title: '第一个殖民地',
          description: '建立你的第一个殖民地',
          icon: '🏠',
          isUnlocked: false,
          unlockedAt: 0,
          category: 'exploration',
          points: 10
        },
        {
          id: 'tech_master',
          title: '科技大师',
          description: '研究10项科技',
          icon: '🔬',
          isUnlocked: false,
          unlockedAt: 0,
          category: 'technology',
          points: 25
        },
        {
          id: 'fleet_commander',
          title: '舰队指挥官',
          description: '建造10艘战舰',
          icon: '🚀',
          isUnlocked: false,
          unlockedAt: 0,
          category: 'military',
          points: 20
        }
      ]
    } catch (error) {
      console.error('加载成就数据失败:', error)
    }
  }

  return {
    // 状态
    gameState,
    gameConfig,
    saveSlots,
    currentEvents,
    achievements,
    
    // 计算属性
    isGameActive,
    gameTimeFormatted,
    completedAchievements,
    achievementProgress,
    
    // 动作
    createNewGame,
    loadGame,
    saveGame,
    pauseGame,
    resumeGame,
    setGameSpeed,
    changeView,
    updateGameTime,
    addEvent,
    removeEvent,
    unlockAchievement,
    updateConfig,
    updateStatistics,
    
    // 游戏控制方法
    setCurrentView,
    togglePause,
    updatePlayTime,
    
    // 事件管理方法
    dismissCurrentEvent,
    acknowledgeEvent,
    makeEventChoice,
    clearProcessedEvents,
    markEventAsProcessed,
    updateLastEventTime,
    processEventChoice,
    
    // 成就系统方法
    isAchievementUnlocked,
    getEvent,
    
    // 初始化方法
    loadGameData,
    initializeStores,
    loadUserSettings
  }
})